package _01_动态数组;

import java.util.Arrays;

public class _977_有序数组的平方 {

    public static void main(String[] args) {
        int[] nums = {-5, -3, -2, 1, 4};
        _977_有序数组的平方 v = new _977_有序数组的平方();
        System.out.println(Arrays.toString(v.sortedSquares(nums)));
    }

    // 不需要平方数组，直接取左边负数就够
    public int[] sortedSquares(int[] nums) {
        int[] newNums = new int[nums.length];
        if (nums == null || nums.length == 0) return newNums;
        int last = nums.length - 1;
        int first = 0;
        int storeIndex = last;
        while (first <= last) {
            // 不需要平方数组，直接取左边负数就够
            if (-nums[first] > nums[last]) {
                newNums[storeIndex--] = nums[first] * nums[first];
                first++;
            } else {
                newNums[storeIndex--] = nums[last] * nums[last];
                last--;
            }
        }
        return newNums;
    }


    // [25,9,4,1,8]
    // [   25.]
    public int[] sortedSquares1(int[] nums) {
        int[] newNums = new int[nums.length];
        if (nums == null || nums.length == 0) return newNums;
        // 读数组所有元素取平方
        for (int i = 0; i < nums.length; i++) {
            nums[i] = nums[i] * nums[i];
        }
        int last = nums.length - 1;
        int first = 0;
        int storeIndex = last;
        while (first <= last) {
            if (nums[first] > nums[last]) {
                newNums[storeIndex--] = nums[first++];
            } else {
                newNums[storeIndex--] = nums[last--];
            }
        }
        return newNums;
    }


}
